package com.erp.auto.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.MaintainBizOrder;
import com.alipay.api.domain.MemberWalletBalanceDetailVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.auto.domain.ErpAutoEvaluationAssociation;
import com.erp.auto.domain.ErpAutoEvaluationCompany;
import com.erp.auto.domain.ErpAutoEvaluationConfig;
import com.erp.auto.domain.ErpAutoEvaluationConfigTask;
import com.erp.auto.mapper.ErpAutoEvaluationAssociationMapper;
import com.erp.auto.mapper.ErpAutoEvaluationCompanyMapper;
import com.erp.auto.mapper.ErpAutoEvaluationConfigTaskMapper;
import com.github.pagehelper.dialect.auto.C3P0AutoDialect;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.oldDomain.BaseEntity;
import com.ruoyi.gather.api.RemoteAeProductStatisticsService;
import com.ruoyi.gather.api.RemoteGatherProductService;
import com.ruoyi.gather.api.domain.dto.EvaluationProductDto;
import com.ruoyi.order.api.RemoteErpOrderService;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.dto.EvaluationDto;
import com.erp.auto.mapper.ErpAutoEvaluationConfigMapper;
import com.erp.auto.service.ErpAutoEvaluationService;
import com.ruoyi.order.api.RemoteErpChildOrderService;
import com.ruoyi.order.api.domain.ErpSellerChildOrder;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.order.api.RemoteEvaluationService;
import com.ruoyi.gather.api.RemoteSellerStoreProductService;
import com.ruoyi.gather.api.RemoteUsdExchangeService;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.order.api.domain.bo.ErpSellerStoreProductEvaluationBo;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.system.api.RemoteCountryCodeService;
import com.ruoyi.system.api.RemoteSysConfigService;
import com.ruoyi.system.api.domain.CountryTwoCode;
import org.apache.poi.ss.formula.functions.Irr;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自动测评
 *
 * @author WXX
 * @date 2023-12-25 14:59:30
 */
@Service
public class ErpAutoEvaluationServiceImpl implements ErpAutoEvaluationService {

    @Resource
    private ErpAutoEvaluationConfigMapper evaluationConfigMapper;
    @Resource
    private ErpAutoEvaluationConfigTaskMapper evaluationConfigTaskMapper;
    @Resource
    private RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    private RemoteErpChildOrderService remoteErpChildOrderService;
    @Resource
    private RemoteSellerStoreProductService remoteSellerStoreProductService;
    @Resource
    private RemoteAeProductStatisticsService remoteAeProductStatisticsService;
    @Resource
    private RemoteUsdExchangeService remoteUsdExchangeService;
    @Resource
    private RemoteCountryCodeService remoteCountryCodeService;
    @Resource
    private RemoteEvaluationService remoteEvaluationService;
    @Resource
    private ErpAutoEvaluationAssociationMapper erpAutoEvaluationAssociationMapper;
    @Resource
    private RemoteErpOrderService remoteErpOrderService;
    @Resource
    private ErpAutoEvaluationCompanyMapper evaluationCompanyMapper;

    /**
     * 执行自动化整体，计划每天上午10点左右执行
     * @return
     */
    @Override
    public R<Object> executeAutoEvaluationConfig() {
        List<ErpAutoEvaluationAssociation> evaluationAssociationList = new ArrayList<>();
        // 获取整体测评配置
        List<ErpAutoEvaluationConfig> configList = evaluationConfigMapper.selectList(new LambdaQueryWrapper<ErpAutoEvaluationConfig>()
                .eq(ErpAutoEvaluationConfig::getStatus, 1));
        for (ErpAutoEvaluationConfig config : configList) {
            // 判断店铺是否有效
            R<Object> r = judgeStoreEmpower(config.getId(), config.getStoreId(), 5);
            if(r.getCode() != 200){
                evaluationAssociationList.add(JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ErpAutoEvaluationAssociation.class));
                continue;
            }
            ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ErpSellerStoreEmpower.class);
            // 判断指定天数内是否有订单
            r = judgeNewOrder(config.getId(), config.getNullOrderDay(), storeEmpower.getStoreUserName(), 5);
            if(r.getCode() != 200){
                evaluationAssociationList.add(JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ErpAutoEvaluationAssociation.class));
                continue;
            }
            // 判断上一单是否为测评单
//            if(config.getIsEvaluation().equals("1")){
//                r = judgeBeforeEvaluationOrder(config.getId(), storeEmpower.getStoreUserName(), 5);
//                if(r.getCode() == 200){
//                    // 是测评单
//                    evaluationAssociationList.add(JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ErpAutoEvaluationAssociation.class));
//                    continue;
//                }
//            }

            // 确认测评单
            r = evaluationOrder(config.getId(), 5 , config.getBeforeDay(), storeEmpower.getStoreUserName(), config.getSort(), config.getShieldProductIds(),
                    config.getAmountMax(), config.getAmountMin(), config.getEvaluationCountry(), config.getStoreId(), config.getRandomRemark());
            evaluationAssociationList.add(JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ErpAutoEvaluationAssociation.class));
        }

        for (ErpAutoEvaluationAssociation association : evaluationAssociationList){
            erpAutoEvaluationAssociationMapper.insert(association);
        }
        return R.ok();
    }


    // TODO 获取单品测评配置，应为订单进入后确认是否满足数量条件，可以考虑采用mq方式

    /**
     * 执行自动化指定日期测评，计划每天8点前执行一次
     * @return
     */
    @Override
    public R<Object> executeAutoEvaluationTask() {
        List<ErpAutoEvaluationAssociation> evaluationAssociationList = new ArrayList<>();
        // 获取指定日期测评配置
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = now.format(formatter);
        List<ErpAutoEvaluationConfigTask> configTaskList = evaluationConfigTaskMapper.selectList(new LambdaQueryWrapper<ErpAutoEvaluationConfigTask>()
                .eq(ErpAutoEvaluationConfigTask::getStatus, 1)
                .apply("DATE(plan_start_time) <= " +"'" +format + "'")
        );
        for (ErpAutoEvaluationConfigTask configTask : configTaskList) {
//            Date planStartTime = configTask.getPlanStartTime();
            // 判断计划执行时间是否是今天以前
            // 判断店铺是否有效
            R<Object> r = judgeStoreEmpower(configTask.getId(), configTask.getStoreId(), 52);
            if(r.getCode() != 200){
                evaluationAssociationList.add(JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ErpAutoEvaluationAssociation.class));
                continue;
            }
            ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ErpSellerStoreEmpower.class);

            // 确认测评单
            // 如果是要测评多单
            for (int integer = 0; integer < configTask.getPlanEvaluationNum(); integer++) {
                r = evaluationOrder(configTask.getId(), 52, configTask.getBeforeDay(), storeEmpower.getStoreUserName(), configTask.getSort(), configTask.getShieldProductIds(),
                        configTask.getAmountMax(), configTask.getAmountMin(), configTask.getEvaluationCountry(), configTask.getStoreId(), configTask.getRandomRemark());
                ErpAutoEvaluationAssociation erpAutoEvaluationAssociation = JSONObject.parseObject(JSONObject.toJSONString(r.getData()), ErpAutoEvaluationAssociation.class);
                // 将测评的productId取出当做屏蔽商品id，保证不刷同一个
                String aeProductId = erpAutoEvaluationAssociation.getAeProductId();
                String shieldProductIds = configTask.getShieldProductIds();
                configTask.setShieldProductIds(shieldProductIds != null ? aeProductId : shieldProductIds + "," + aeProductId);
                evaluationAssociationList.add(erpAutoEvaluationAssociation);
            }
            
        }

        for (ErpAutoEvaluationAssociation association : evaluationAssociationList){
            // 根据type和id 找到task，修改状态
            Integer type = association.getType();
            if (type == 52) {
                ErpAutoEvaluationConfigTask task = evaluationConfigTaskMapper.selectById(association.getConfigId());
                if (task != null) {
                    if (association.getEvaluationId() == null) {
                        // 失败
                        task.setStatus(-1);
                    }else {
                        task.setStatus(3);
                    }
                    evaluationConfigTaskMapper.updateById(task);
                }
            }
//            erpAutoEvaluationAssociationMapper.insert(association);
        }
        
        return R.ok();
    }

    /**
     * 执行公司刷单（每天执行一次）
     * 3天未出单， 新店铺第一次上品时间 7天 金额60~200
     * 周六日，节假日 不执行
     */
    public void executeAutoEvaluationCompany() {
        LocalDate now = LocalDate.now();
        DayOfWeek dayOfWeek = now.getDayOfWeek();
        if (dayOfWeek.equals(DayOfWeek.SATURDAY) || dayOfWeek.equals(DayOfWeek.SUNDAY))
            return;
        // 获取到店铺
        List<ErpAutoEvaluationCompany> evaluationList = evaluationCompanyMapper.selectList(new LambdaQueryWrapper<>());
//        List<String> cnList = evaluationList.stream().map(ErpAutoEvaluationCompany::getStoreUserName).collect(Collectors.toList());
        ErpAutoEvaluationAssociation erpAutoEvaluationAssociation = new ErpAutoEvaluationAssociation();
        for (ErpAutoEvaluationCompany evaluationCompany : evaluationList) {
            String storeUserName = evaluationCompany.getStoreUserName();
            R<Object> sellerStoreEmpowerByCnCode = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(storeUserName);
            if (sellerStoreEmpowerByCnCode.getCode() != 200) {
                erpAutoEvaluationAssociation.setType(2);
                erpAutoEvaluationAssociation.setRemark("查询不到店铺：" + storeUserName);
                erpAutoEvaluationAssociation.setConfigId(null);
                erpAutoEvaluationAssociation.setCreateTime(new Date());
                erpAutoEvaluationAssociationMapper.insert(erpAutoEvaluationAssociation);
                continue;
            }
            ErpSellerStoreEmpower empower = JSONObject.parseObject(JSONObject.toJSONString(sellerStoreEmpowerByCnCode.getData()), ErpSellerStoreEmpower.class);
            R<Object> objectR = judgeStoreEmpower(null, empower.getId(), 2);
            if(objectR.getCode() != 200){
                erpAutoEvaluationAssociation = JSONObject.parseObject(JSONObject.toJSONString(objectR.getData()), ErpAutoEvaluationAssociation.class);
                erpAutoEvaluationAssociationMapper.insert(erpAutoEvaluationAssociation);
                continue;
            }
            objectR = judgeCompany(storeUserName, empower.getId(), evaluationCompany.getId());
            if (objectR != null) {
                erpAutoEvaluationAssociation = JSONObject.parseObject(JSONObject.toJSONString(objectR.getData()), ErpAutoEvaluationAssociation.class);
                erpAutoEvaluationAssociationMapper.insert(erpAutoEvaluationAssociation);
            }
        }
    }

    private R<Object> judgeCompany(String cn, Long storeId, Long configId) {
        // 1、判断近三天是否有单（有单跳过）
        R<Object> orderR = remoteErpOrderService.getNewestOrderByStoreUserName(cn);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        ErpAutoEvaluationAssociation association = new ErpAutoEvaluationAssociation();
        association.setConfigId(configId);
        association.setCreateTime(new Date());
        association.setType(2);
        if (orderR.getCode() != 200) {
            association.setRemark("获取订单失败：" + orderR.getMsg());
            return R.fail(association);
        }
        
        LocalDate currentDate = LocalDate.now();
        ErpSellerOrder sellerOrder = JSONObject.parseObject(JSONObject.toJSONString(orderR.getData()), ErpSellerOrder.class);
        if (sellerOrder == null || sellerOrder.getGmtCreate() == null) {
            // 没有订单，造一个7天之外的
            sellerOrder = new ErpSellerOrder();
            sellerOrder.setGmtCreate("2024-04-15 00:00:00");
        }
        String gmtCreate = sellerOrder.getGmtCreate();
        LocalDateTime givenTime = LocalDateTime.parse(gmtCreate, formatter);
        LocalDate outOrderDate = givenTime.toLocalDate();
        long daysDiff = ChronoUnit.DAYS.between(outOrderDate, currentDate);
        if (Math.abs(daysDiff) > 3) {
            // 2、 判断店铺是否是新店 获取第一次上品时间
            ErpSellerStoreProduct farthestProduct = remoteSellerStoreProductService.getFarthestProduct(cn);
            if (farthestProduct != null && farthestProduct.getCreateTime() != null) {
                // 是否相差7天
                Date createTime = farthestProduct.getCreateTime();
                Instant instant = createTime.toInstant();
                ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
                LocalDateTime farthestTime = zonedDateTime.toLocalDateTime();
                LocalDate farthestDate = farthestTime.toLocalDate();
                long farthestDiff = ChronoUnit.DAYS.between(farthestDate, currentDate);
                if (Math.abs(farthestDiff) < 7) {
                    // 2.1 新店 判断7天订单
                    if (Math.abs(daysDiff) > 7) {
                        // 刷单
                        return evaluationOrder(configId, 11, 3, cn, "0,1,2,3", null, "200", "60"
                                , "KR,JP,US", storeId, 0);
                    }
                }
                else {
                    // 2.2 老店 刷单
                    return evaluationOrder(configId, 11, 3, cn, "0,1,2,3", null, "200", "60"
                            , "KR,JP,US", storeId, 0);
                }
            }
        }
        
        return null;
    }

    /**
     * 判断店铺是否有效
     * @param configId
     * @param storeId
     * @return
     */
    private R<Object> judgeStoreEmpower(Long configId, Long storeId, Integer type){
        ErpAutoEvaluationAssociation erpAutoEvaluationAssociation = new ErpAutoEvaluationAssociation();
        // 判断店铺是否删除或授权失效
        R<Object> storeEmpowerR = remoteSellerStoreService.getSellerStoreEmpowerByStoreId(storeId.toString());
        if(storeEmpowerR.getCode() != 200){
            erpAutoEvaluationAssociation.setConfigId(configId);
            erpAutoEvaluationAssociation.setType(type);
            erpAutoEvaluationAssociation.setRemark("未查到店铺授权信息");
            erpAutoEvaluationAssociation.setCreateTime(new Date());
            return R.fail(erpAutoEvaluationAssociation);
        }
        String storeEmpowerStr = JSONObject.toJSONString(storeEmpowerR.getData());
        ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(storeEmpowerStr, ErpSellerStoreEmpower.class);
        if (storeEmpower == null) {
            erpAutoEvaluationAssociation.setConfigId(configId);
            erpAutoEvaluationAssociation.setType(type);
            erpAutoEvaluationAssociation.setRemark("未查到店铺授权信息");
            erpAutoEvaluationAssociation.setCreateTime(new Date());
            return R.fail(erpAutoEvaluationAssociation);
        }
        if (!"1".equals(storeEmpower.getIsEmpower())) {
            erpAutoEvaluationAssociation.setConfigId(configId);
            erpAutoEvaluationAssociation.setType(type);
            erpAutoEvaluationAssociation.setRemark("店铺未授权或授权已过期");
            erpAutoEvaluationAssociation.setCreateTime(new Date());
            return R.fail(erpAutoEvaluationAssociation);
        }
        return R.ok(storeEmpower);
    }

    /**
     * 判断指定天数内是否有订单
     * @param configId
     * @param nullOrderDay
     * @param storeUserName
     * @return
     */
    private R<Object> judgeNewOrder(Long configId, String nullOrderDay, String storeUserName, Integer type){
        ErpAutoEvaluationAssociation erpAutoEvaluationAssociation = new ErpAutoEvaluationAssociation();
        //判断店铺指定范围天数内是否出单
        R<Object> orderR = remoteErpChildOrderService.getChildOrdersByBeforeDays(Integer.valueOf(nullOrderDay), storeUserName, null);
        if (orderR.getCode() == 200){
            erpAutoEvaluationAssociation.setConfigId(configId);
            erpAutoEvaluationAssociation.setType(type);
            erpAutoEvaluationAssociation.setRemark("店铺" + nullOrderDay + "日内有新订单");
            erpAutoEvaluationAssociation.setCreateTime(new Date());
            return R.fail(erpAutoEvaluationAssociation);
        }
        return R.ok();
    }

    /**
     * 确认测评单
     * @param configId
     * @param beforeDay
     * @param storeUserName
     * @param sort
     * @param shieldProductIds
     * @param maxBig
     * @param minBig
     * @param evaluationCountry
     * @param storeId
     * @param randomRemark
     * @return
     */
    private R<Object> evaluationOrder(Long configId, Integer type, Integer beforeDay, String storeUserName,
                                      String sort, String shieldProductIds, String maxBig,
                                      String minBig, String evaluationCountry, Long storeId, Integer randomRemark){
        // 将要测评的商品
        String skuCode = null;
        String productPrice = null;
        Long aeProductId = null;
        // 没有出单获取近N天的自然单
        ErpAutoEvaluationAssociation erpAutoEvaluationAssociation = new ErpAutoEvaluationAssociation();
        R<Object> orderR = remoteErpChildOrderService.getChildOrdersByBeforeDays(beforeDay, storeUserName, shieldProductIds);
        List<ErpSellerChildOrder> whileChildOrderList = new ArrayList<>();
        if (orderR.getCode() == 200) {
            String orderStr = JSONObject.toJSONString(orderR.getData());
            whileChildOrderList = JSONObject.parseArray(orderStr, ErpSellerChildOrder.class);
            Iterator<ErpSellerChildOrder> iterator = whileChildOrderList.iterator();
            while (iterator.hasNext()) {
                ErpSellerChildOrder next = iterator.next();
                Long productId = next.getProductId();
                // 剔除掉不符合条件的
                // 有可能前几天的刷单还没有下单，所以测评表七天内的商品也不刷
                // 找出每个商品最新的一条订单是不是 疑似测评单，是的话这个商品不刷，剔除
                Boolean isEvaluation = remoteEvaluationService.sevenDaysEvaluation(productId);
                Boolean suspectedOrder = remoteEvaluationService.judgeSuspected(productId, 1L);
                if (suspectedOrder || isEvaluation) {
                    iterator.remove();
                }
            }
            
        }
        
        List<EvaluationProductDto> evaluationProductList = remoteAeProductStatisticsService.getEvaluationProduct(storeId, shieldProductIds, maxBig, minBig);
        for (EvaluationProductDto dto : evaluationProductList) {
            ErpSellerChildOrder childOrder = new ErpSellerChildOrder();
            childOrder.setSkuCode(dto.getSkuCode());
            childOrder.setProductPrice(dto.getProductPrice());
            childOrder.setProductId(dto.getProductId());
            whileChildOrderList.add(childOrder);
        }
        
        // 判断排序
        if (sort == null || sort.equals("")){
            sort = "0,1,2,3";
        }
        String[] split = sort.split(",");
//        String[] newArray = new String[split.length + 1];

        // 是否出单 排第一个
//        newArray[0] = "X";

        // 将原数组的所有元素复制到新数组的其余位置  
//        System.arraycopy(split, 0, newArray, 1, split.length);
        // 进入循环的商品
        EvaluationDto evaluationDto = null;
        List<EvaluationDto> evaluationDtoList = null;
        boolean flag = true;
        while (flag) {
            if (whileChildOrderList.size() == 0) {
                break;
            }
            
            for (String condition : split) {
                // 按顺序找订单 TODO 以下逻辑等数据模块完善后，全部调整为调用数据模块，根据天数和店铺查询订单数最多、加购数、收藏数、访问数等条件的sku
//                if (condition.equals("0")) {
//                    // 获取订单数量最多的
//                    Map<Long, Long> skuCountMap = whileChildOrderList.stream()
//                            .collect(Collectors.groupingBy(ErpSellerChildOrder::getProductId, Collectors.counting()));
//
//                    List<Long> skuCodeWithMaxCount = skuCountMap.entrySet().stream()
//                            .filter(entry -> Objects.equals(entry.getValue(), skuCountMap.values().stream().max(Long::compare).get()))
//                            .map(Map.Entry::getKey)
//                            .collect(Collectors.toList());
//                    // 判断是否是多个，多个再找
//                    if (skuCodeWithMaxCount.size() == 1) {
////                        skuCode = skuCodeWithMaxCount.get(0);
//                        aeProductId = skuCodeWithMaxCount.get(0);
//                        Long tem = aeProductId;
//                        List<ErpSellerChildOrder> childOrders = whileChildOrderList.stream().filter(str -> str.getProductId().equals(tem)).collect(Collectors.toList());
//                        productPrice = childOrders.get(0).getProductPrice();
//                        erpAutoEvaluationAssociation.setRemark("订单量最大");
//                        flag = false;
//                        break;
//                    }
//                    else {
//                        // 根据找到哪些订单商品，进入下一个循环
//                        List<ErpSellerChildOrder> childOrderList = new ArrayList<>();
//                        for (Long productId : skuCodeWithMaxCount) {
//                            for (ErpSellerChildOrder childOrder : whileChildOrderList) {
//                                if (productId.equals(childOrder.getProductId())) {
//                                    childOrderList.add(childOrder);
//                                    break;
//                                }
//                            }
//                        }
//                        whileChildOrderList = childOrderList;
//                    }
//                }
//                else 
                {
                    // 比较加购数
                    Set<Long> productIds = whileChildOrderList.stream().map(ErpSellerChildOrder::getProductId)
                            .collect(Collectors.toSet());
                    // 根据商品id获取加购数
                    evaluationDtoList = new ArrayList<>();
                    int max = 0; // 最大加购数
                    R<Object> evaluationDtoR = null;
                    for (Long productId : productIds) {
//                        if (condition.equals("X")) {
//                            // 判断近几日是否出单
//                            
//                        }else {
                            evaluationDtoR = remoteErpChildOrderService.getProductOperationsData(productId.toString(), condition);
//                        }
                        if (evaluationDtoR.getCode() != 200) {
                            continue;
                        }
                        String evaluationDtoStr = JSONObject.toJSONString(evaluationDtoR.getData());
                        evaluationDto = JSONObject.parseObject(evaluationDtoStr, EvaluationDto.class);
                        if (evaluationDto.getNumber() == max) {

                            evaluationDtoList.add(evaluationDto);
                        }
                        if (evaluationDto.getNumber() > max) {
                            //清空列表并把最大的加入
                            max = evaluationDto.getNumber();
                            evaluationDtoList = new ArrayList<>();
                            evaluationDtoList.add(evaluationDto);
                        }
                    }
                    int tem = max;
                    // 将最大加购数的商品id取出来
                    List<EvaluationDto> evaluationDtos = evaluationDtoList.stream().filter(str -> str.getNumber() == (tem)).collect(Collectors.toList());
                    List<ErpSellerChildOrder> childOrderList = new ArrayList<>();
                    if (evaluationDtos.size() == 1) {
                        // 找到属于这个商品id的订单
                        EvaluationDto evaluationDto1 = evaluationDtos.get(0);
                        Long productId = evaluationDto1.getProductId();
                        for (ErpSellerChildOrder childOrder : whileChildOrderList) {
                            if (Objects.equals(productId, childOrder.getProductId())) {
                                skuCode = childOrder.getSkuCode();
                                aeProductId = childOrder.getProductId();
                                productPrice = childOrder.getProductPrice();
                                if (condition.equals("1")) {
                                    erpAutoEvaluationAssociation.setRemark("加购数最多");
                                }else if (condition.equals("2")) {
                                    erpAutoEvaluationAssociation.setRemark("收藏数最多");
                                }else if (condition.equals("3")) {
                                    erpAutoEvaluationAssociation.setRemark("访客数最多");
                                }else if (condition.equals("0")){
                                    erpAutoEvaluationAssociation.setRemark("出单量最多");
                                }
                                break;
                            }
                        }
                        break;
                    }
                    else {
                        for (EvaluationDto dto : evaluationDtos) {
                            Long productId = dto.getProductId();
                            for (ErpSellerChildOrder childOrder : whileChildOrderList) {
                                if (Objects.equals(productId, childOrder.getProductId())) {
                                    childOrderList.add(childOrder);
                                    break;
                                }
                            }
                        }
                        whileChildOrderList = childOrderList;
                    }
                }
            }

            // 真有条件完全一样的就随便刷一单

            if (skuCode == null) {
                ErpSellerChildOrder childOrder = whileChildOrderList.get(0);
                productPrice = childOrder.getProductPrice();
                skuCode = childOrder.getSkuCode();
                aeProductId = childOrder.getProductId();
                erpAutoEvaluationAssociation.setRemark("加购数最多");
            }
            
                BigDecimal skuBig = new BigDecimal(productPrice);
                int number = judgeEvaluationNumber(new BigDecimal(maxBig), new BigDecimal(minBig), skuBig);
                if (number != 0) {
//                    flag = false;
                    // 转为美元
                    R<Object> usdR = remoteUsdExchangeService.getExchangeByTime(DateUtils.getTime(),"USD");
                    BigDecimal bankConversionPri = new BigDecimal(usdR.getData().toString());
                    skuBig = skuBig.divide(bankConversionPri.movePointLeft(2), RoundingMode.UP);
                    R<Object> objectR = evaluationSubmit(skuBig, aeProductId, skuCode, evaluationCountry, storeId
                            ,(long) number, randomRemark, type);
                    if (objectR.getCode() != 200) {
                        String msg = objectR.getMsg();
                        erpAutoEvaluationAssociation.setConfigId(configId);
                        erpAutoEvaluationAssociation.setRemark(msg);
                        erpAutoEvaluationAssociation.setType(type);
                        erpAutoEvaluationAssociation.setCreateTime(new Date());
                        return R.fail(erpAutoEvaluationAssociation);
                    }
                    else {
                        Long evaluationId = Long.valueOf(objectR.getData().toString());
                        erpAutoEvaluationAssociation.setConfigId(configId);
                        erpAutoEvaluationAssociation.setEvaluationId(evaluationId);
                        erpAutoEvaluationAssociation.setType(type);
                        erpAutoEvaluationAssociation.setCreateTime(new Date());
                        erpAutoEvaluationAssociation.setAeProductId(aeProductId.toString());
                        erpAutoEvaluationAssociation.setSkuCode(skuCode);
                        return R.ok(erpAutoEvaluationAssociation);
                    }
                }
                else {
                    // 去掉这个品的订单再循环
                    String sku = skuCode;
                    whileChildOrderList.removeIf(childOrder -> childOrder.getSkuCode().equals(sku));
                    skuCode = null;
                    flag = true;
                }
            }
//            else {
//                // 去掉这个品的订单再循环
//                String sku = skuCode;
//                whileChildOrderList.removeIf(childOrder -> childOrder.getSkuCode().equals(sku));
//                skuCode = null;
//                flag = true;
//            }
        
        erpAutoEvaluationAssociation.setConfigId(configId);
        erpAutoEvaluationAssociation.setRemark("自动测评失败，没有满足条件的商品");
        erpAutoEvaluationAssociation.setType(type);
        erpAutoEvaluationAssociation.setCreateTime(new Date());
        return R.fail(erpAutoEvaluationAssociation);
    }

    //判断金额，返回刷单数量
    private static Integer judgeEvaluationNumber(BigDecimal amountMax, BigDecimal amountMin, BigDecimal skuPrice) {
        if (skuPrice.compareTo(amountMax) <= 0) {
            if (skuPrice.compareTo(amountMin) <= 0) {
                BigDecimal number = amountMin.divide(skuPrice,2, RoundingMode.DOWN);
                return number.intValue() + 1;
            }
            else {
                return 1;
            }
        }
        else {
            return 0;
        }
    }

    // 提交刷单
    private R<Object> evaluationSubmit(BigDecimal skuBig, Long aeProductId, String skuCode,
                                       String evaluationCountry, Long storeId,
                                       Long number, Integer randomRemark, Integer type) {
        ErpSellerStoreProductSku sellerStoreProductSku = new ErpSellerStoreProductSku();
        sellerStoreProductSku.setAeProductId(aeProductId);
        sellerStoreProductSku.setSkuCode(skuCode);
        R<Object> storeProductSkuR = remoteSellerStoreProductService.getSellerStoreProductSkuListInfo(sellerStoreProductSku);
        if(storeProductSkuR.getCode() == 200){
            String storeProductSkuStr = JSONObject.toJSONString(storeProductSkuR.getData());
            List<ErpSellerStoreProductSku> skuList = JSONObject.parseArray(storeProductSkuStr, ErpSellerStoreProductSku.class);
            if(skuList != null && skuList.size() > 0){
                sellerStoreProductSku = skuList.get(0);
            }
        }

        if (sellerStoreProductSku != null) {

            // 开始刷单
            ErpSellerStoreProductEvaluationBo evaluationBo = new ErpSellerStoreProductEvaluationBo();
            skuBig = skuBig.multiply(new BigDecimal(number)).setScale(2, RoundingMode.UP);
            evaluationBo.setSkuPrice(skuBig.toString());
            evaluationBo.setSellerStoreProductId(sellerStoreProductSku.getSellerStoreProductId());
            evaluationBo.setProductSkuId(sellerStoreProductSku.getId());
            evaluationBo.setType(type);
            // 提交刷单页面数据
            Date evaluationTime = randomDate(null, null);
            evaluationBo.setEvaluationTime(evaluationTime);
            // 随机国家
            String country = randomCountry(evaluationCountry, storeId, aeProductId);
            evaluationBo.setCountry(country);
            // 随机留言
            if (randomRemark == 1) {
                evaluationBo.setLeaveInfo(randomRemark());
            }
            evaluationBo.setNumber(number);
            evaluationBo.setLink("https://www.aliexpress.com/item/" + sellerStoreProductSku.getAeProductId() + ".html");
//                        evaluationBo.setStoreLink("https://www.aliexpress.com/store/");

            // 以下迁移至gather模块


            evaluationBo.setStoreId(storeId);
            // 商品价格转为美元

            return remoteEvaluationService.submit(evaluationBo);
        }
        return R.fail("找不到商品");
    }

    // 随机时间
    private Date randomDate(String startTime, String endTime) {
        if(startTime == null || startTime.equals("")){
            startTime = "09:00:00";
        }
        if(endTime == null || endTime.equals("")){
            endTime = "15:00:00";
        }
        List<String> startList = Arrays.stream(startTime.split(":")).collect(Collectors.toList());
        LocalTime start = LocalTime.of(Integer.parseInt(startList.get(0)), Integer.parseInt(startList.get(1)));
        List<String> endList = Arrays.stream(endTime.split(":")).collect(Collectors.toList());
        LocalTime end = LocalTime.of(Integer.parseInt(endList.get(0)), Integer.parseInt(endList.get(1)));

        long duration = ChronoUnit.MINUTES.between(start, end);
        Random random = new Random();
        long randomMinutes = random.nextInt((int) duration);
        LocalTime randomTime = start.plusMinutes(randomMinutes);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime randomDateTime = LocalDateTime.of(LocalDate.from(now), randomTime);
        // 生成一个随机分钟数，然后转换为一个时间对象
        System.out.println(randomDateTime);
        Instant instant = randomDateTime.atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    // 随机国家
    private String randomCountry(String countryStr, Long storeId, Long aeProductId) {
        String country = null;
        List<String> startList = Arrays.stream(countryStr.split(",")).collect(Collectors.toList());
        String cookie = remoteSellerStoreService.getCookieByStoreId(storeId);
        // 获取单品分析国家
        Map<String, Object> map = new HashMap<>();
        map.put("cookie_str", cookie);
        map.put("productId", aeProductId.toString());
        map.put("days", "30");
        RestTemplate restTemplate = new RestTemplate();
        // TODO 后面将IP和链接配置到nacos里，参考chatGpt工具类
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://47.94.131.193:8000" + "/single/analysis", map, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        try {
            JSONObject jsonObjectData = jsonObject.getJSONObject("data").getJSONObject("data");
            if (ObjectUtils.isNotEmpty(jsonObjectData)) {
                JSONArray arrayModel = jsonObjectData.getJSONObject("data").getJSONArray("model");
                for (Object item : arrayModel) {
                    JSONObject model = (JSONObject) item;
                    String countryId = model.getString("countryId");
                    R<Object> countryTwoCodeR = remoteCountryCodeService.getByCountryCn(countryId);
                    if (countryTwoCodeR.getCode() == 200) {
                        CountryTwoCode countryTwoCode = JSONObject.parseObject(JSONObject.toJSONString(countryTwoCodeR.getData()), CountryTwoCode.class);
                        if (countryTwoCode != null) {
                            String isoCode = countryTwoCode.getIsoCode();
                            if (startList.contains(isoCode)) {
                                country = isoCode;
                            }
                        }
                    }
                }
            }
        }catch (Exception ignored) {
            
        }
        if (country == null) {
            Random random = new Random();
            int i = random.nextInt(startList.size());
            country = startList.get(i);
        }
        return country;
    }

    // 随机备注（3~6位）
    public String randomRemark() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random rng = new Random();
        int length = rng.nextInt(4) + 3;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = rng.nextInt(characters.length());
            char randomChar = characters.charAt(index);
            builder.append(randomChar);
        }
        return builder.toString();
    }

}
